#include "../header/Save.h"

using namespace std;

bool is_readable(const std::string & file) {
	std::ifstream fichier(file.c_str());
	return !fichier.fail();
}

void existance() {
	using std::cout;
	if (is_readable("save.txt")) {
		cout << "Fichier existant et lisible.\n";
	} else {
		cout << "Fichier inexistant ou non lisible.\n";
	}
}

void test_lecture() {
	ifstream file("save.txt");
	if (!file) {
		cerr << "Erreur d'ouverture\n";
		return;
	}

	string line;
	if (!(file >> line)) {
		cerr << "Erreur de lecture\n";
		return;
	}
}

void test_ecriture() {
	ofstream file("save.txt");
	if (!file) {
		cerr << "Erreur de creation\n";
		return;
	}

	file << "Une ligne\n";
	if (!file) {
		cerr << "Erreur d'Ecriture" << endl;
		return;
	}

}

void save(Joueur *j1, Joueur *j2, int tour, int robot) {

	string mot = "";
	Pion *pTmp;
	int i = 0;
	int b = j1->getNbPion();
	std::ofstream file("save.txt");


	//on sauvagarde un int qui indique si il y a ou non un ordi qui joue
	file<<robot<<endl;
	//on sauvegarde les coordonnees de Impala

	file << j1->getMap()->getImpala()->getPosX() << " "
			<< j1->getMap()->getImpala()->getPosY() << " " << endl;

// on sauvegarde les info du joueur1
	file << j1->getNom() << " " << j1->getNumero() << " " << j1->getScore()
			<< " " << j1->getNbPion() << " " << j1->isInauguration() << endl;

	//on sauvegarde la main du joueur1

	pTmp = j1->donnePion(i);

	while (b > 0) {
		mot = pTmp->getName();

		file << mot << " ";
		i++;
		pTmp = j1->donnePion(i);
		b--;
		mot = "";

	}

	file << endl;

	i = 0;
	b = j2->getNbPion();
	pTmp = j2->donnePion(i);

	mot = "";
	file << j2->getNom() << " " << j2->getNumero() << " " << j2->getScore()
			<< " " << j2->getNbPion() << " " << j2->isInauguration() << endl;

	pTmp = j2->donnePion(i);

	while (b > 0) {
		mot = pTmp->getName();

		file << mot << " ";
		i++;
		pTmp = j2->donnePion(i);
		b--;
		mot = "";

	}

	file << endl;
	//on sauvegarde le tour des joueurs
		file<<tour<<endl;
	//on sauvegarde le type de map
		file<<j1->getMap()->isPresident()<<endl;

	//on sauvegarde la map
	for (i = 1; i < 6; i++) {

		for (int j = 1; j < 7; j++) {

			pTmp = j1->getMap()->getPlateau(i, j)->getP();
			if (pTmp != NULL) {

				file << pTmp->getName() << " " << pTmp->getCouleur() << " "
						<< pTmp->isFace() << " ";
			}
			if (pTmp == NULL) {

				file << "." << " " << "-" << " " << "-" << " ";
			}
		}
		file << endl;
	}

	file.close();
}
